import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import '../core/auth/user_manager.dart';
import '../route/route_utils.dart';
import '../route/routes.dart';

class SplashPage extends StatefulWidget {
  const SplashPage({super.key});

  @override
  State<SplashPage> createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage>
    with SingleTickerProviderStateMixin {
  final UserManager _userManager = UserManager();
  late AnimationController _controller;
  late Animation<double> _fadeAnimation;
  late Animation<double> _scaleAnimation;

  @override
  void initState() {
    super.initState();

    // 初始化动画控制器
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 1000),
    );

    _fadeAnimation = Tween<double>(begin: 0, end: 1).animate(
      CurvedAnimation(parent: _controller, curve: Curves.easeIn),
    );

    _scaleAnimation = Tween<double>(begin: 0.9, end: 1.0).animate(
      CurvedAnimation(parent: _controller, curve: Curves.easeOutBack),
    );

    _controller.forward();

    // 动画结束后检查登录状态
    _controller.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        _checkLoginStatus();
      }
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  Future<void> _checkLoginStatus() async {
    final l10n = AppLocalizations.of(context)!;

    await Future.delayed(const Duration(milliseconds: 300)); // 给个过渡动画时间

    // 1. 检查是否开启安全锁
    final enableLock = await _userManager.isBiometricLockEnabled();
    if (enableLock) {
      final ok = await _userManager.biometricService
          .authenticate(reason: l10n.securitySettingsBiometricLocalizedReason);
      if (!ok) {
        if (mounted) {
          RouteUtils.pushNamedAndRemoveUntil(context, RoutePath.login);
        }
        return;
      }
    }

    // 2. 启动时加载 + 校验
    await _userManager.loadAndValidateOnLaunch();

    if (mounted) {
      if (!_userManager.isLoggedIn) {
        // 没有登录信息 → 去登录页
        RouteUtils.pushNamedAndRemoveUntil(context, RoutePath.login);
        return;
      }
      RouteUtils.pushNamedAndRemoveUntil(context, RoutePath.home);
    }
  }

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;
    final isDark = Theme.of(context).brightness == Brightness.dark;

    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: isDark
                ? [
                    colorScheme.surfaceContainerHighest,
                    colorScheme.surface,
                  ]
                : [
                    colorScheme.primary.withOpacity(0.05), // 顶部非常浅
                    colorScheme.primaryContainer.withOpacity(0.25), // 底部柔和
                  ],
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
          ),
        ),
        child: Center(
          child: Card(
            margin: EdgeInsets.symmetric(horizontal: 12.w),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(16.r),
            ),
            elevation: 2,
            color: colorScheme.surface,
            child: FadeTransition(
              opacity: _fadeAnimation,
              child: ScaleTransition(
                scale: _scaleAnimation,
                child: Image.asset(
                  'assets/images/app_logo.jpg',
                  fit: BoxFit.fill,
                  // 保留原图圆角
                  filterQuality: FilterQuality.high,
                  isAntiAlias: true,
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
